package cn.com.dashihui.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Admin;
import cn.com.dashihui.web.service.AdminService;
import cn.com.dashihui.web.service.ResourceService;

public class SystemController extends BaseController{
	private ResourceService resourceService = new ResourceService();
	private AdminService adminService = Duang.duang(AdminService.class);
    
	/**
	 * 跳转登录成功页
	 */
	public void index() {
		render("login.jsp");
	}
	
	/**
	 * 跳转到主页
	 */
	public void home() {
		render("home.jsp");
	}
    public void login(){
        this.render("login.jsp");
    }
    
	/**
	 * 跳转住框架页
	 */
	public void main() {
		if (getCurrentUser()==null) {
			render("login.jsp");
		}else {
			render("main.jsp");
		}
		
	}
    
    /**
     * 分页
     */
    public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		String beginDate=getPara("beginDate");
		String endDate=getPara("endDate");
		renderResult(0,adminService.findByTotle(pageNum,pageSize,beginDate,endDate));
	}
    
    /**
     * 登录操作
     * @return 1：用户名为空，2：密码为空，3：用户名或密码错误，4：网络繁忙...
     */
    public void doLogin(){
        try {
        	String username = getPara("username");
        	String password = getPara("password");
        	if(StrKit.isBlank(username)){
        		//用户名为空
                this.renderResult(1);
        	}else if(StrKit.isBlank(password)){
        		//密码为空
                this.renderResult(2);
        	}else{
        		//根据入参创建token
        		boolean rememberMe = getParaToBoolean("rememberMe",false);
        		String host = getRequest().getRemoteHost();
        		UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, password, rememberMe, host);
        		//认证
        		Subject currentUser = SecurityUtils.getSubject();
        		currentUser.login(authenticationToken);
        		Admin currUser = (Admin)currentUser.getPrincipal();
        		//查询登录用户可操作的菜单
        		this.setSessionAttr("navMenus", resourceService.findMenuResourcesByUser(currUser.getInt("id")));
        		//登录成功
        		this.renderSuccess();
        	}
        } catch (AuthenticationException e) {
        	//e.printStackTrace();
        	logger.error("登录失败");
        	//用户名或者密码错误
            this.renderResult(3);
        } catch (Exception e) {
        	e.printStackTrace();
            //网络繁忙...
            this.renderResult(4);
        }
    }
    
	public void toEditMinePwd(){
		render("editMinePwd.jsp");
	}
	
	/**
	 * 更新当前登录用户的密码
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	public void doEditMinePwd(){
		//原密码
		String passwordOld = getPara("passwordOld");
		//新设密码
		String passwordNew = getPara("passwordNew");
		if(StrKit.isBlank(passwordOld)){
			renderResult(1);
			return;
		}else if(StrKit.isBlank(passwordNew)){
			renderResult(2);
			return;
		}else if(passwordNew.length()>100){
			renderResult(3);
			return;
		}else{
			//更新
			try {
				if(adminService.editMinePwd(getCurrentUser(),passwordOld,passwordNew)){
					renderSuccess();
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
				//原密码输入错误
				renderResult(4);
				return;
			}
		}
		renderFailed();
	}

    public void logout() {
        Subject currentUser = SecurityUtils.getSubject();
        try {
        	if(currentUser.isAuthenticated())currentUser.logout();
            this.redirect("/login");
        } catch (SessionException ise) {
        	logger.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        } catch (Exception e) {
        	logger.debug("登出发生错误", e);
        }
    }
    
    public void error401(){
    	render("401.jsp");
    }
    
    public void error403(){
    	render("403.jsp");
    }
    
    public void error404(){
    	render("404.jsp");
    }
    
    public void error500(){
    	render("500.jsp");
    }
    /**
     * 首页导出
     */
    public void doExcel(){
    	List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("date", "日期"));
	    titles.add(new Pair("daySale", "日销售额"));
	    titles.add(new Pair("dayorder", "日交易单数"));
	    titles.add(new Pair("daydui", "日使用兑换码"));
	    titles.add(new Pair("dayweidui", "未使用兑换码"));
	    titles.add(new Pair("daylook", "日浏览量"));
	    titles.add(new Pair("dayhuo", "日活跃"));
	    titles.add(new Pair("dayhui", "日新增会员数"));
	    titles.add(new Pair("dayXorder", "线下日交易单数"));
	    titles.add(new Pair("dayXsale", "线下日交易额"));
	    String beginDate=getPara("beginDate");
	    String endDate=getPara("endDate");
		List<Record> list=adminService.findExcelByPage(beginDate, endDate);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
				record.set("date",list.get(i).get("RepDate"));
				record.set("daySale", list.get(i).get("daySale"));
				record.set("dayorder", list.get(i).get("dayorder"));
				record.set("daydui", list.get(i).get("daydui"));
				record.set("dayweidui", list.get(i).get("dayweidui"));
				record.set("daylook", list.get(i).get("daylook"));
				record.set("dayhuo", list.get(i).get("dayhuo"));
				record.set("dayhui", (list.get(i).get("usNum")==null)?0:list.get(i).get("usNum"));
				record.set("dayXorder", (list.get(i).get("ofNum")==null)?0:list.get(i).get("ofNum"));
				record.set("dayXsale", (list.get(i).get("ofSum")==null)?0:Double.parseDouble(list.get(i).get("ofSum").toString()));
			listz.add(record);
 		}
		// 导出
		adminService.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
}
